package javabasic.singleton.lanhanshi;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 线程不安全的懒汉式单例模式
 */
public class Singleton04 {
    private static Singleton04 INSTANCE;
    private Singleton04(){}
    public static Singleton04 getInstance(){
        if (INSTANCE==null){
            System.out.println("创建对象");
            INSTANCE=new Singleton04();
        }
        return INSTANCE;
    }

    public static void main(String[] args) throws Exception{
        //因为是单线程运行所以结果肯定是true  但是构造方法只会执行一次
        //Singleton04 instance = Singleton04.getInstance();
        //Singleton04 instance1 = Singleton04.getInstance();
        //System.out.println(instance==instance1);

        //多线程运行是否是单例
        Callable<Singleton04> singlton04Callable = new Callable<Singleton04>(){
            @Override
            public Singleton04 call() throws Exception {
                return Singleton04.getInstance();
            }
        };

        //创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        Future<Singleton04> future = threadPool.submit(singlton04Callable);
        Future<Singleton04> future1 = threadPool.submit(singlton04Callable);
        Singleton04 instance = future.get();
        Singleton04 instance1 = future1.get();
        System.out.println(instance==instance1);
        threadPool.shutdown();

    }
}
